package com.ocss.ocsscustomerserver.tools;


import com.alibaba.fastjson.JSONObject;
import com.ocss.ocsscommon.message.ClientMessage;
import com.ocss.ocsscommon.message.KafkaMessage;
import com.ocss.ocsscommon.message.KafkaVisitorAssignMessage;
import com.ocss.ocsscustomerserver.model.ClientMessage.ClientEstablishMessage;
import com.ocss.ocsscustomerserver.model.ClientMessageWarpper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * @Auther: lijiang
 * @Date: 2023-04-17 21:08
 * @Description: MessagePost
 */

@Component
public class MessagePost {
    @Autowired
    WebsocketRecorder websocketRecorder;

    public  void  sendMessage(KafkaMessage kafkaMessage) throws IOException {
        ClientMessage clientMessage = ClientMessage.builder()
                .to(kafkaMessage.getReceiveId())
                .from(kafkaMessage.getSendId())
                .type(kafkaMessage.getType())
                .data(kafkaMessage.getData()).build();

        ClientMessageWarpper clientMessageWarpper =  new ClientMessageWarpper<ClientMessage>(6000, clientMessage);
        this.inform(clientMessageWarpper, clientMessage.getTo());
    }

    //通知服务人员访客退出
    public  void informSessionExit (KafkaVisitorAssignMessage kafkaVisitorAssignMessage) throws IOException {
        this.informSessionOpe(kafkaVisitorAssignMessage, 5001);
    }


    public  void informSessionEstablish (KafkaVisitorAssignMessage kafkaVisitorAssignMessage)throws IOException {
            this.informSessionOpe(kafkaVisitorAssignMessage, 5000);
    }

    public void informSessionOpe (KafkaVisitorAssignMessage kafkaVisitorAssignMessage, int code) throws IOException {
        ClientEstablishMessage clientEstablishMessage = new ClientEstablishMessage();
        BeanUtils.copyProperties(kafkaVisitorAssignMessage,clientEstablishMessage);

        ClientMessageWarpper clientMessageWarpper =  new ClientMessageWarpper<ClientEstablishMessage>(code, clientEstablishMessage);
        this.inform(clientMessageWarpper, clientEstablishMessage.getCustomer());
    }



    //像服务人员发送通知
    public  void inform (ClientMessageWarpper clientMessageWarpper, String sessionId) throws IOException {
        WebSocketSession session = websocketRecorder.getSession(sessionId);
        if (session == null) {
            System.out.println("目标客服不存在");
            return;
        }
        session.sendMessage(new TextMessage(JSONObject.toJSONString(clientMessageWarpper)));
    }
}
